import type {RouteRecordRaw} from 'vue-router'
import {createRouter, createWebHashHistory, type NavigationGuardNext, type RouteLocationNormalized} from 'vue-router';
import LoginVue from '@/views/login/index.vue'
import RegisterVue from '@/views/register/index.vue'
import {Message} from "@arco-design/web-vue";
import PageLoadingBar, { type LoadingBarInstance } from '@/components/PageLoadingBar/index.vue';
import {createApp} from "vue";
import {userCurrent} from "@/api/userApi";
import type {User} from "@/types/User";

// 创建加载条实例并挂载到body
const app = createApp(PageLoadingBar);
// @ts-ignore
const loadingBar = app.mount(document.body.appendChild(document.createElement('div'))) as LoadingBarInstance;

// 扩展路由表中 meta 对象中的属性
declare module 'vue-router' {
  interface RouteMeta {
    title?: string; // 菜单标题
    icon?: string; // 菜单图标
    linkTo?: string; // 外链地址
    cache?: boolean; // 是否缓存, 将 name放到include属性上 <keep-alive include="xxx"></keep-alive>
    hidden?: boolean; // 是否左侧菜单中显示，true隐藏/false显示
    isBreadcrumd?: boolean; // 是否显示到面包屑中 默认或true会显示，false不显示
    hasChildren?: boolean; // 是否含有子菜单
    requiresAdmin?: boolean; // 新增：是否需要管理员权限
  }
}


export const menuRouter: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Layout',
    redirect: '/user/login',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home/index.vue'),
        meta: {
          title: '首页',
          icon: 'icon-home',
          cache: true,
          hidden: false,
          hasChildren: false,
          isBreadcrumd: true,
          requiresAdmin: false
        }
      },
      {
        path: '/management',
        name: 'Management',
        meta: {
          title: '管理页',
          icon: 'icon-settings',
          hidden: false,
          hasChildren: true,
          isBreadcrumd: true,
          requiresAdmin: false // 管理页本身不需要管理员权限
        },
        children: [
          {
            path: '/user/manage',
            name: 'UserManage',
            component: () => import('@/views/userManage/index.vue'),
            meta: {
              title: '用户管理',
              icon: 'icon-stamp',
              cache: true,
              hidden: false,
              hasChildren: false,
              isBreadcrumd: true,
              requiresAdmin: true // 新增：用户管理需要管理员权限
            }
          }
        ]
      },
      {
        path: '/userInfo',
        name: 'User',
        meta: {
          title: '用户信息',
          icon: 'icon-user',
          cache: true,
          hidden: false,
          hasChildren: true,
          isBreadcrumd: true,
          requiresAdmin: false
        },
        children: [
          {
            path: '/person/userInfo',
            name: 'UserInfo',
            component: () => import('@/views/userInfo/index.vue'),
            meta: {
              title: '个人主页',
              icon: 'icon-stamp',
              cache: true,
              hidden: false,
              hasChildren: false,
              isBreadcrumd: true,
              requiresAdmin: false
            }
          },
          {
            path: '/person/editUserInfo',
            name: 'EditUserInfo',
            component: () => import('@/views/editUserInfo/index.vue'),
            meta: {
              title: '个人设置',
              icon: 'icon-stamp',
              cache: true,
              hidden: false,
              hasChildren: false,
              isBreadcrumd: true,
              requiresAdmin: false
            }
          },
        ]
      },
    ],
  },
  {
    path: '/user/login',
    component: LoginVue,
    meta: {
      id: 'login',
      name: "登录",
      icon: '',
      hidden: true,
      hasChildren: false,
      requiresAdmin: false
    }
  },
  {
    path: '/user/register',
    component: RegisterVue,
    meta: {
      id: 'register',
      name: "注册",
      icon: '',
      hidden: true,
      hasChildren: false,
      requiresAdmin: false
    }
  },
];

const routes: Array<RouteRecordRaw> = [...menuRouter];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 路由守卫中控制加载条
let timer: number;
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  // 现在 TypeScript 能识别 start() 方法了
  timer = loadingBar.start();
  next();
});

router.afterEach((to: RouteLocationNormalized, from: RouteLocationNormalized, failure?: Error | void) => {
  clearInterval(timer);
  // 现在 TypeScript 能识别 finish() 方法了
  loadingBar.finish(!failure);
});

const whiteList = ['/user/login', '/user/register'];

// 获取用户角色信息
const getCurrentUser = async (): Promise<number> => {
  try {
    const res: User = await userCurrent();
    // @ts-ignore
    return res.data;
  } catch (error) {
    console.error('获取用户角色失败：', error);
    return 0; // 默认返回普通用户角色
  }
};

// 合并后的路由守卫
router.beforeEach(async (to, from, next) => {
  try {
    const res = await getCurrentUser();
    // 1. 处理白名单页面
    if (whiteList.includes(to.path)) {
      // 已登录用户访问登录/注册页时自动跳转首页
      // @ts-ignore
      if (res.code === 0) {
        next('/');
        return;
      }
      next();
      return;
    }

    // @ts-ignore
    if (res.code > 0) {
      Message.warning('暂无身份，请登录注册');
      next(`/user/login?redirect=${to.fullPath}`);
      return;
    }

    // 3. 已登录状态：检查权限要求
    if (to.meta.requiresAdmin) {
      // @ts-ignore
      if (res.data.userRole === 1) {
        next(); // 管理员权限验证通过
      } else {
        Message.error('权限不足，请联系管理员');
        // 跳转回来源页或首页
        next(from.path && from.path !== '/user/login' ? from.path : '/home');
      }
    } else {
      // 不需要管理员权限，直接放行
      next();
    }
  } catch (error) {
    console.error('路由守卫错误：', error);
    Message.error('服务器异常，请稍后重试');
    next('/user/login');
  }
});


export default router

